package model

import (
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ SysFileTagModel = (*customSysFileTagModel)(nil)

type (
	// SysFileTagModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysFileTagModel.
	SysFileTagModel interface {
		sysFileTagModel
		withSession(session sqlx.Session) SysFileTagModel
		FindList(ctx context.Context, userId int64) ([]SysFileTag, error)
		FindPage(ctx context.Context, offset int, size int, userId int64) ([]SysFileTag, error)
		FindCount(ctx context.Context, userId int64) (int, error)
		FindByName(ctx context.Context, title string, userId int64) ([]SysFileTag, error)
	}

	customSysFileTagModel struct {
		*defaultSysFileTagModel
	}
)

func (m *customSysFileTagModel) FindByName(ctx context.Context, title string, userId int64) ([]SysFileTag, error) {
	query := fmt.Sprintf("select %s from %s where title = ? and user_id = ?  ", sysFileTagRows, m.table)
	var tag []SysFileTag
	err := m.conn.QueryRowsCtx(ctx, &tag, query, title, userId)
	if err != nil {
		return nil, err
	}
	return tag, nil
}

func (m *customSysFileTagModel) FindCount(ctx context.Context, userId int64) (int, error) {
	query := fmt.Sprintf("select count(*) from %s where user_id = ? ", m.table)
	var count int
	err := m.conn.QueryRowCtx(ctx, &count, query, userId)
	if err != nil {
		return 0, err
	}
	return count, err
}

func (m *customSysFileTagModel) FindPage(ctx context.Context, offset int, size int, userId int64) ([]SysFileTag, error) {
	query := fmt.Sprintf("select %s from %s where user_id = ? order by createTime desc  limit  ?,?  ", sysFileTagRows, m.table)
	var tags []SysFileTag
	err := m.conn.QueryRowsCtx(ctx, &tags, query, userId, offset, size)
	if err != nil {
		return nil, err
	}
	return tags, nil
}

func (m *customSysFileTagModel) FindList(ctx context.Context, userId int64) ([]SysFileTag, error) {
	query := fmt.Sprintf("select %s from %s where user_id = ? order  by createTime desc ", sysFileTagRows, m.table)
	var tags []SysFileTag
	err := m.conn.QueryRowsCtx(ctx, &tags, query, userId)
	if err != nil {
		return nil, err
	}
	return tags, nil

}

// NewSysFileTagModel returns a model for the database table.
func NewSysFileTagModel(conn sqlx.SqlConn) SysFileTagModel {
	return &customSysFileTagModel{
		defaultSysFileTagModel: newSysFileTagModel(conn),
	}
}

func (m *customSysFileTagModel) withSession(session sqlx.Session) SysFileTagModel {
	return NewSysFileTagModel(sqlx.NewSqlConnFromSession(session))
}
